package net.zjitc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/9/28.
 */
@WebServlet(name = "LastAccessTimeServlet",urlPatterns = "/lastAccessTimeServlet")
public class LastAccessTimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();

        String s = "lastAccessTime";
        String name = "";
        String currentTime = new SimpleDateFormat("yyyy-MM-dd#hh:mm:ss").format(new Date());
        Cookie cookie = new Cookie("lastAccessTime",currentTime);

        for (int i = 0; cookies!=null&&i<cookies.length ; i++) {
            name = cookies[i].getName();
            if(s.equals(name)){
                String date = cookies[i].getValue();
                out.write("上次访问时间为"+date);
                response.addCookie(cookie);
            }
        }
        if(!s.equals(name)){
            out.write("第一次访问 访问时间"+currentTime);
            response.addCookie(cookie);
        }
    }
}
